package cn.kgc.javaweb.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author: mosin
 * @version: v1.0  2022/6/7
 * 数据库连接工具类
 */
public final class DruidUtil {

    private  static  DataSource dataSource;

    private DruidUtil(){}

    static{

        InputStream resourceAsStream = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            //创建连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接池
    public  static  DataSource getDataSource(){
        return dataSource;
    }

    //获取连接
    public  static Connection getConnection(){
        Connection connection = null;
        try {
            connection  = dataSource.getConnection();
            return connection;
        } catch (SQLException throwables) {
                throwables.printStackTrace();
        }
        return connection;
    }

    //释放资源

    public static  void closeAll(ResultSet resultSet, Statement statement,Connection connection){

        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}
